/*
 * Copyright 2004 original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jbfilter.impl;

import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import org.jbfilter.core.FilterComponent;

abstract class _FilterComponentBeanSupport<E, C extends FilterComponent<E>> {
	
	private C filterComponent;
	
	_FilterComponentBeanSupport(C filterComponent) {
		this.filterComponent = filterComponent;
	}

	public C getFilterComponent() {
		return filterComponent;
	}
	
	public void filterOut(LinkedList<E> coll) {
		if (!filterComponent.isActive()) {
			return;
		}
		for (Iterator<E> iterator = coll.iterator(); iterator.hasNext();) {
			E o = iterator.next();
			if (!pass(o)) {
				iterator.remove();
			}
		}
	}

	public List<E> filter(Collection<E> toFilter) {
		LinkedList<E> retour = new LinkedList<E>(toFilter);
		filterOut(retour);
		return retour;
	}
	
	public boolean pass(E bean) {
		Boolean passFromCallback = callBackFromFilterComponentBeanSupport(bean);
		if (passFromCallback == null) {
			// always pass, even if inverted
			return true;
		}
		return filterComponent.isInverted() ? !passFromCallback.booleanValue() : passFromCallback.booleanValue();
	}
	/**
	 * {@code null} means, ignore criteria, let pass and also ignore {@code inverted}.
	 * @param bean
	 * @return
	 */
	abstract Boolean callBackFromFilterComponentBeanSupport(E bean);
}
